﻿#include "ssTimerThread.h"
#include "../ssTime.h"

namespace StarSeeker
{

ssTimerThread::ssTimerThread()
{
}

ssTimerThread::~ssTimerThread()
{
	ExitThread();
}

u32 ssTimerThread::AddNewTimer(u32 msgType, u64 timestamp, u32 interval, ulint p1, ulint p2)
{
	u32 id = 0;
	SS_MUTEX_LOCK(m_mutex)
		id = AddTimer(msgType, timestamp, interval, p1, p2);
	SS_MUTEX_UNLOCK(m_mutex)
	return id;
}

void ssTimerThread::StartHalfHourTimer()
{
	SS_MUTEX_LOCK(m_mutex)
		StartHalfTimer();
	SS_MUTEX_UNLOCK(m_mutex)
}

u32 ssTimerThread::AddNewTimer(u32 msgType, u32 interval, ulint param1, ulint param2)
{
	return AddNewTimer(msgType, ssTime::GetTimeNow().u64p + interval, interval, param1, param2);
}

void ssTimerThread::DeleteTimer(u32 timerId)
{
	SS_MUTEX_LOCK(m_mutex);
	RemoveTimer(timerId);
	SS_MUTEX_UNLOCK(m_mutex);
}

void ssTimerThread::ThreadMemberFunc()
{
	ssTimer_s top;
	while (!IsRequestStop())
	{
		top.msgID = SS_TIMER_DEL;
		u64 now = ssTime::GetTimeNow().u64p;

		SS_MUTEX_LOCK(m_mutex);
		if (m_msgHeap.Count() > 0)
		{
			top = m_msgHeap.Top();
			if (now > top.timestamp)
			{
				m_msgHeap.Pop();
			}
			else
			{
				top.msgID = SS_TIMER_DEL;
			}
		}
		SS_MUTEX_UNLOCK(m_mutex);

		switch (top.msgID)
		{
		case SS_TIMER_ONCE://单次计时器
			{
				//Dispatch(top.msgID, top.subID, top.param[0], top.param[1]);
				OnTimerOnce(top.subID, top.param[0], top.param[1]);
			}
			break;
		case SS_TIMER_REPEAT://重复计时器
			{
				//Dispatch(top.msgID, top.subID, top.param[0], top.param[1]);
				OnTimerHalfHour(top.subID, top.param[0], top.param[1]);
				top.timestamp = now + top.interval;
				SS_MUTEX_LOCK(m_mutex);
				m_msgHeap.Push(top);
				SS_MUTEX_UNLOCK(m_mutex);
			}
			break;
		case SS_TIMER_HALF_HOUR://半点计时器
			{
				//Dispatch(top.msgID, top.subID, top.param[0], top.param[1]);
				OnTimerHalfHour(top.subID, top.param[0], top.param[1]);
				u32 beg = 1800 - now % 1800;
				top.timestamp = now + beg;
				SS_MUTEX_LOCK(m_mutex);
				m_msgHeap.Push(top);
				SS_MUTEX_UNLOCK(m_mutex);
			}
			break;
		case SS_THREAD_STOP:
			RequestStop();
			break;
		default:
			break;
		}
		ssThreadBase::Sleep(200);
	}
}

void ssTimerThread::ExitThread()
{
	RequestStop();
}

StarSeeker::ulint ssTimerThread::GetTimerCount()
{
	return m_msgHeap.Count();
}

}
